<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<BackButton />
			<p>钱包提现</p>
		</header>

		<!-- 提现表单 -->
		<div class="withdraw-form">
			<!-- 账户余额显示 -->
			<div class="balance-display">
				<p class="balance-label">可用余额</p>
				<p class="balance-amount">¥{{ availableBalance }}</p>
			</div>

			<!-- 提现金额输入 -->
			<div class="form-group">
				<label>提现金额</label>
				<div class="input-wrapper">
					<span class="currency">¥</span>
					<input 
						type="number" 
						v-model="amount" 
						placeholder="请输入提现金额"
						@input="validateAmount"
						min="0"
						step="0.01"
					/>
				</div>
				<p class="hint" v-if="withdrawRate < 1">
					手续费率：{{ (withdrawRate * 100).toFixed(2) }}%，实际到账：¥{{ actualAmount }}
				</p>
			</div>

			<!-- 支付密码输入 -->
			<div class="form-group">
				<label>支付密码</label>
				<div class="input-wrapper">
					<input 
						type="password" 
						v-model="payPwd" 
						placeholder="请输入支付密码"
						maxlength="6"
					/>
				</div>
			</div>

			<!-- 快捷金额选择 -->
			<div class="quick-amounts">
				<h3 class="section-title">快捷金额</h3>
				<div class="amount-buttons">
					<button 
						v-for="quickAmount in quickAmounts" 
						:key="quickAmount"
						class="amount-btn"
						:class="{ active: amount == quickAmount }"
						@click="selectAmount(quickAmount)"
						:disabled="quickAmount > availableBalance"
					>
						¥{{ quickAmount }}
					</button>
				</div>
			</div>

			<!-- 提现说明 -->
			<div class="withdraw-info">
				<h3 class="section-title">提现说明</h3>
				<ul>
					<li>提现金额不能超过可用余额</li>
					<li v-if="withdrawRate < 1">提现将收取{{ ((1 - withdrawRate) * 100).toFixed(2) }}%的手续费</li>
					<li>提现将在1-3个工作日内到账</li>
				</ul>
			</div>

			<!-- 提交按钮 -->
			<div class="submit-section">
				<button class="submit-btn" @click="submitWithdraw" :disabled="!isValid || loading">
					<span v-if="loading">提现中...</span>
					<span v-else>确认提现</span>
				</button>
			</div>
		</div>

		<!-- 底部菜单部分 -->
		<AppFooter></AppFooter>
	</div>
</template>

<script>
	import AppFooter from '../components/AppFooter.vue';
	import BackButton from '../components/BackButton.vue';
	export default {
		name: 'WalletWithdraw',
		data() {
			return {
				amount: '',
				payPwd: '',
				loading: false,
				availableBalance: '0.00',
				quickAmounts: [50, 100, 200, 500],
				withdrawRate: 0.9,
				walletInfo: {},
				user: null
			}
		},
		computed: {
			actualAmount() {
				if (!this.amount || parseFloat(this.amount) <= 0) return '0.00';
				const amount = parseFloat(this.amount);
				return (amount * this.withdrawRate).toFixed(2);
			},
			isValid() {
				const num = parseFloat(this.amount);
				return !isNaN(num) && num > 0 && num <= parseFloat(this.availableBalance) && this.payPwd.length >= 6;
			}
		},
		created() {
			let user = this.$getSessionStorage('user');
			if (user == null) {
				this.$router.push('/login');
				return;
			}
			this.user = user;
			this.loadWalletInfo();
			this.loadWithdrawRules();
		},
		methods: {
			loadWalletInfo() {
				this.$axios.post('wallet/info', this.$qs.stringify({
					walletId: this.user.userId
				})).then(response => {
					if (response.data && (response.data.code === 200 || response.data.code === '200')) {
						const result = response.data.result || {};
						this.walletInfo = result;
						// 直接使用DTO返回的availableBalance字段
						if (result.availableBalance) {
							this.availableBalance = result.availableBalance;
						} else if (result.balance) {
							// 兼容旧格式
							const balance = parseFloat(result.balance || 0);
							const frozen = parseFloat(result.frozenAmount || 0);
							this.availableBalance = (balance - frozen).toFixed(2);
						} else {
							this.availableBalance = '0.00';
						}
					} else {
						this.availableBalance = '0.00';
					}
				}).catch(error => {
					console.error('获取钱包信息失败:', error);
					this.availableBalance = '0.00';
				});
			},
			loadWithdrawRules() {
				this.$axios.post('WalletRuleController/getWithdrawRule').then(response => {
					if (response.data && (response.data.code === 200 || response.data.code === '200') && response.data.result) {
						const rule = response.data.result;
						this.withdrawRate = parseFloat(rule.withdrawRate || 0.9);
					}
				}).catch(error => {
					console.error('获取提现规则失败:', error);
				});
			},
			selectAmount(amount) {
				if (amount > parseFloat(this.availableBalance)) {
					this.$toast?.error('提现金额不能超过可用余额');
					return;
				}
				this.amount = amount.toString();
				this.validateAmount();
			},
			validateAmount() {
				if (!this.amount) return;
				const num = parseFloat(this.amount);
				if (num <= 0) {
					this.$toast?.error('提现金额必须大于0');
				} else if (num > parseFloat(this.availableBalance)) {
					this.$toast?.error('提现金额不能超过可用余额');
				}
			},
			submitWithdraw() {
				if (!this.isValid) {
					if (!this.amount || parseFloat(this.amount) <= 0) {
						this.$toast?.error('请输入有效的提现金额');
					} else if (parseFloat(this.amount) > parseFloat(this.availableBalance)) {
						this.$toast?.error('提现金额不能超过可用余额');
					} else if (this.payPwd.length < 6) {
						this.$toast?.error('请输入支付密码');
					}
					return;
				}

				const withdrawAmount = parseFloat(this.amount);
				const actual = parseFloat(this.actualAmount);
				if (!confirm(`确认提现 ¥${withdrawAmount.toFixed(2)} 吗？\n扣除手续费后实际到账：¥${actual}`)) {
					return;
				}

				this.loading = true;
				this.$axios.post('wallet/withdraw', this.$qs.stringify({
					walletId: this.user.userId,
					payPwd: this.payPwd,
					amount: withdrawAmount
				})).then(response => {
					if (response.data && (response.data.code === 200 || response.data.code === '200')) {
						// 触发钱包余额更新事件
						if (window.dispatchEvent) {
							window.dispatchEvent(new CustomEvent('wallet-balance-updated', { bubbles: true }));
						}
						this.$toast?.success('提现申请成功！');
						setTimeout(() => {
							// 再次触发事件，确保钱包页面收到
							if (window.dispatchEvent) {
								window.dispatchEvent(new CustomEvent('wallet-balance-updated', { bubbles: true }));
							}
							this.$router.go(-1);
						}, 1500);
					} else {
						this.$toast?.error(response.data.message || '提现失败');
					}
				}).catch(error => {
					console.error(error);
					this.$toast?.error('提现失败，请稍后重试');
				}).finally(() => {
					this.loading = false;
				});
			}
		},
		components: {
			AppFooter,
			BackButton
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 顶部应用栏 */
	header {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
		gap: 16px;
	}

	header p {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/****************** 提现表单 ******************/
	.withdraw-form {
		margin-top: 0;
		padding: 4vw;
		padding-top: 20px;
		padding-bottom: 120px;
	}

	.balance-display {
		background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
		border-radius: 12px;
		padding: 6vw;
		text-align: center;
		margin-bottom: 4vw;
		color: #fff;
		box-shadow: 0 4px 12px rgba(0,0,0,0.1);
	}

	.balance-label {
		font-size: 3.5vw;
		opacity: 0.9;
		margin-bottom: 2vw;
	}

	.balance-amount {
		font-size: 8vw;
		font-weight: bold;
		margin: 0;
	}

	.form-group {
		background-color: #fff;
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.form-group label {
		display: block;
		font-size: 3.5vw;
		color: #666;
		margin-bottom: 3vw;
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		border: 2px solid #e0e0e0;
		border-radius: 8px;
		padding: 3vw;
		transition: border-color 0.3s;
	}

	.input-wrapper:focus-within {
		border-color: #0097FF;
	}

	.currency {
		font-size: 5vw;
		color: #333;
		margin-right: 2vw;
		font-weight: 500;
	}

	.input-wrapper input {
		flex: 1;
		border: none;
		outline: none;
		font-size: 4.5vw;
		color: #333;
	}

	.hint {
		margin-top: 2vw;
		font-size: 3vw;
		color: #ff9800;
	}

	/****************** 快捷金额 ******************/
	.quick-amounts {
		background-color: #fff;
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.section-title {
		font-size: 4vw;
		color: #666;
		margin: 0 0 3vw 0;
		font-weight: 500;
	}

	.amount-buttons {
		display: flex;
		flex-wrap: wrap;
		gap: 2vw;
	}

	.amount-btn {
		flex: 1;
		min-width: calc(50% - 1vw);
		padding: 3vw;
		border: 2px solid #e0e0e0;
		border-radius: 8px;
		background-color: #fff;
		color: #333;
		font-size: 4vw;
		cursor: pointer;
		transition: all 0.3s;
	}

	.amount-btn:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

	.amount-btn.active {
		border-color: #0097FF;
		background-color: #0097FF;
		color: #fff;
	}

	.amount-btn:active:not(:disabled) {
		transform: scale(0.95);
	}

	/****************** 提现说明 ******************/
	.withdraw-info {
		background-color: #fff;
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.withdraw-info ul {
		margin: 0;
		padding-left: 5vw;
	}

	.withdraw-info li {
		font-size: 3.5vw;
		color: #666;
		line-height: 1.8;
		margin-bottom: 1.5vw;
	}

	/****************** 提交按钮 ******************/
	.submit-section {
		padding: 4vw;
	}

	.submit-btn {
		width: 100%;
		padding: 4vw;
		background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
		color: #fff;
		border: none;
		border-radius: 12px;
		font-size: 4.5vw;
		cursor: pointer;
		transition: all 0.3s;
		box-shadow: 0 4px 12px rgba(245, 87, 108, 0.4);
	}

	.submit-btn:disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.submit-btn:active:not(:disabled) {
		transform: scale(0.98);
	}
</style>

